#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简化的污染类型服务（无缓存）
直接调用原始服务，移除所有缓存逻辑
"""

from typing import List, Dict, Any, Optional
from services.pollution_type_service import pollution_type_service
from core.logging_config import get_logger

logger = get_logger("pollution_type_service_cached")


class PollutionTypeCachedService:
    """简化的污染类型服务（无缓存）"""

    def __init__(self):
        # 不需要缓存管理器
        pass

    def get_all_pollution_types(self, customer_id: str = "default", active_only: bool = True) -> List[Any]:
        """获取所有污染类型"""
        logger.debug(f"获取污染类型列表: customer_id={customer_id}, active_only={active_only}")
        return pollution_type_service.get_all_pollution_types(customer_id, active_only)

    def get_pollution_type_by_id(self, customer_id: str, pollution_type_id: int) -> Optional[Any]:
        """根据ID获取污染类型"""
        logger.debug(f"根据ID获取污染类型: ID={pollution_type_id}")
        return pollution_type_service.get_pollution_type_by_id(customer_id, pollution_type_id)

    def get_pollution_type_by_code(self, customer_id: str, code: str) -> Optional[Any]:
        """根据代码获取污染类型"""
        logger.debug(f"根据代码获取污染类型: CODE={code}")
        return pollution_type_service.get_pollution_type_by_code(customer_id, code)

    def get_pollution_type_examples(self, customer_id: str, pollution_type_id: Optional[int] = None, active_only: bool = True) -> List[Any]:
        """获取污染类型样例"""
        if pollution_type_id is None:
            # 获取所有样例
            logger.debug(f"获取所有样例: customer_id={customer_id}, active_only={active_only}")
            return pollution_type_service.get_all_examples(customer_id)

        logger.debug(f"获取污染类型样例: ID={pollution_type_id}, active_only={active_only}")
        return pollution_type_service.get_pollution_type_examples(customer_id, pollution_type_id, active_only)

    def create_pollution_type(self, customer_id: str, type_data: Dict[str, Any]) -> Dict[str, Any]:
        """创建污染类型"""
        logger.info(f"创建污染类型: {type_data.get('name', 'Unknown')}")
        ptype = pollution_type_service.create_pollution_type(customer_id, type_data)
        return {"id": ptype.id, "code": ptype.code, "name": ptype.name}

    def update_pollution_type(self, customer_id: str, pollution_type_id: int, type_data: Dict[str, Any]) -> Dict[str, Any]:
        """更新污染类型"""
        logger.info(f"更新污染类型: ID={pollution_type_id}")
        ptype = pollution_type_service.update_pollution_type(customer_id, pollution_type_id, type_data)
        return {"id": ptype.id, "code": ptype.code, "name": ptype.name}

    def delete_pollution_type(self, customer_id: str, pollution_type_id: int) -> bool:
        """删除污染类型"""
        logger.info(f"删除污染类型: ID={pollution_type_id}")
        return pollution_type_service.delete_pollution_type(customer_id, pollution_type_id)

    def create_pollution_type_example(self, customer_id: str, pollution_type_id: int, example_data: Dict[str, Any]) -> Dict[str, Any]:
        """创建污染类型样例"""
        logger.info(f"创建污染类型样例: 类型ID={pollution_type_id}")
        example = pollution_type_service.create_pollution_type_example(customer_id, pollution_type_id, example_data)
        return {"id": example.id, "pollution_type_id": pollution_type_id}

    def update_pollution_type_example(self, customer_id: str, example_id: int, example_data: Dict[str, Any]) -> Dict[str, Any]:
        """更新污染类型样例"""
        logger.info(f"更新污染类型样例: ID={example_id}")
        example = pollution_type_service.update_pollution_type_example(customer_id, example_id, example_data)
        return {"id": example.id, "pollution_type_id": example.pollution_type_id}

    def delete_pollution_type_example(self, customer_id: str, example_id: int) -> bool:
        """删除污染类型样例"""
        logger.info(f"删除污染类型样例: ID={example_id}")
        return pollution_type_service.delete_pollution_type_example(customer_id, example_id)

    def get_pollution_type_tree(self, customer_id: str, active_only: bool = True) -> Dict[str, Any]:
        """获取污染类型树结构"""
        logger.debug(f"获取污染类型树结构: customer_id={customer_id}, active_only={active_only}")
        types = self.get_all_pollution_types(customer_id, active_only)
        return self._build_tree_structure(types)

    def _build_tree_structure(self, types: List[Any]) -> Dict[str, Any]:
        """构建树结构"""
        from collections import defaultdict

        # 按层级分组
        by_level = defaultdict(list)
        for ptype in types:
            by_level[ptype.level].append(ptype)

        # 按父级关系组织
        tree = {
            "nodes": [],
            "edges": []
        }

        # 添加所有节点
        node_id_map = {}
        for ptype in types:
            node_id = f"type_{ptype.id}"
            node_id_map[ptype.id] = node_id

            tree["nodes"].append({
                "id": node_id,
                "label": ptype.name,
                "code": ptype.code,
                "level": ptype.level,
                "category": ptype.tag_category,
                "data": {
                    "id": ptype.id,
                    "code": ptype.code,
                    "name": ptype.name,
                    "level": ptype.level,
                    "tag_category": ptype.tag_category,
                    "usage_scope": ptype.usage_scope,
                    "exclusion_scope": ptype.exclusion_scope
                }
            })

        # 添加边关系
        for ptype in types:
            if ptype.parent_code:
                # 查找父节点
                parent = next((p for p in types if p.code == ptype.parent_code), None)
                if parent:
                    tree["edges"].append({
                        "from": node_id_map[parent.id],
                        "to": node_id_map[ptype.id]
                    })

        return tree

    def get_pollution_types_for_analysis(self, customer_id: str) -> List[Dict[str, Any]]:
        """获取用于分析的污染类型"""
        logger.debug(f"获取分析用污染类型: customer_id={customer_id}")
        types = self.get_all_pollution_types(customer_id, active_only=True)

        # 过滤出用于分析的污染类型
        analysis_types = []
        for ptype in types:
            examples = self.get_pollution_type_examples(customer_id, ptype.id, active_only=True)
            if examples:  # 只有包含样例的类型才用于分析
                analysis_types.append({
                    "id": ptype.id,
                    "code": ptype.code,
                    "name": ptype.name,
                    "level": ptype.level,
                    "tag_category": ptype.tag_category,
                    "examples_count": len(examples),
                    "avg_confidence": sum(ex.confidence_level for ex in examples) / len(examples) if examples else 0,
                    "examples": examples
                })

        return analysis_types

    def get_pollution_type_statistics(self, customer_id: str) -> Dict[str, Any]:
        """获取污染类型统计信息"""
        logger.debug(f"获取污染类型统计信息: customer_id={customer_id}")
        types = self.get_all_pollution_types(customer_id, active_only=False)
        examples = self.get_pollution_type_examples(customer_id, None, active_only=False)

        stats = {
            "total_types": len(types),
            "active_types": len([t for t in types if t.is_active]),
            "total_examples": len(examples),
            "active_examples": len([e for e in examples if e.is_active]),
            "types_by_level": {},
            "types_by_category": {},
            "examples_by_type": {}
        }

        # 按层级统计
        for ptype in types:
            level = ptype.level
            if level not in stats["types_by_level"]:
                stats["types_by_level"][level] = 0
            stats["types_by_level"][level] += 1

        # 按分类统计
        for ptype in types:
            category = ptype.tag_category or "未分类"
            if category not in stats["types_by_category"]:
                stats["types_by_category"][category] = 0
            stats["types_by_category"][category] += 1

        # 按类型统计样例
        for example in examples:
            type_id = example.pollution_type_id
            if type_id not in stats["examples_by_type"]:
                stats["examples_by_type"][type_id] = 0
            stats["examples_by_type"][type_id] += 1

        return stats

    def warm_up_cache(self, customer_id: str):
        """缓存预热（无缓存版本，仅记录日志）"""
        logger.info(f"缓存预热请求（无缓存版本）: customer_id={customer_id}")
        # 无缓存操作，仅记录日志


# 创建全局服务实例
pollution_type_cached_service = PollutionTypeCachedService()